# 自定义上下文管理器类
class File():
    def __init__(self,filename,filemode):
        self.filename=filename
        self.filemode=filemode

    def __enter__(self):
        # 上下文方法，负责操作对象资源，比如文件对象，数据库连接对象
        self.file=open(self.filename,self.filemode)
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()

# with结合上下文对象
if __name__ == '__main__':
    with File("1.txt","r") as file:
        filedata=file.read()
        print(filedata)